Skip to left side bar
>
  • File
  • Edit
  • View
  • Run
  • Kernel
  • Tabs
  • Settings
  • Help
PyPI Manager

Warning

The JupyterLab development team is excited to have a robust third-party extension community. However, we do not review third-party extensions, and some extensions may introduce security risks or contain malicious code that runs on your machine. Moreover in order to work, this panel needs to fetch data from web services. Do you agree to activate this feature?
Please read the privacy policy.

Installed

No entries

Discover

No entries

Open Tabs

    Kernels

      Language servers

        Terminals

          Table of Contents

          No Headings

          The table of contents shows headings in notebooks and supported files.

          /sandboxes/homework-5-new-tlhaksa1/
          Name
          ...
          Last Modified
          File Size
          • hw5.ipynb20 minutes ago1.3 MB
          • README.md11 hours ago1.9 KB
          • sankey.html11 hours ago3.5 MB
          • stacked_bars.html12 hours ago3.5 MB
          • README.md
          • hw5.ipynb
          • stacked_bars.html
          • sankey.html
          99
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          [![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-24ddc0f5d75046c5622901739e7c5dd533143b0c8e959d652212380cedb1ea36.svg)](https://classroom.github.com/a/YXOeu4qD)

          1. Create a python file that webscrapes GDP by country and plots a stacked interactive bar plot using plotly. Stack countries within regions using the IMF numbers. Please include this in your ipython notebook and output your plot to an html file containing the plot.
          2. Look at the chapter on interactive graphics and, specifically, the code to display a subject's MRICloud data as a sunburst plot. Do the following. Display this subject's data as a Sankey diagram. Display as many levels as you can (at least 3) for Type = 1, starting from the intracranial volume.
          3. Create a simple webpage containing the Sankey graphic and host it on github pages. Do not- host this off of your assignment repo from github classroom, since this is not public. Instead, you'll have to create a new public repo from your regular github account and add this file. Put the link to your live web page in a markdown cell of your hw5.ipynb file as a text block.

          Your homework should include
          1. An file called hw5.ipynb that has your code for parts 1 and 2.
          2. Two html files, one called sankey.html and one called stacked_bar.html that contain the two plots as html files.
          3. Your hw3.ipynb file should have a text block that contains a link to the live and publicly hosted sankey diagram.


          Remember that you should have two repositories for this assignment. First, you need the HW repository that you create when you accept the assignment. This should contain the three files (hw5.ipynb, sankey.html, stacked_bar.html). Secondly, you will need to create your own repository containing a live link to your sankey html file. So, when I click on that link it should show a page containing your plot.

          Note plotly objects contain a method called to_html() which is useful for creating an html file.
          Kernel status: Unknown
          # Part 1

          Part 1¶

          [48]:
          import requests as rq
          import bs4
          import pandas as pd
          [50]:
          Selection deleted
          # read webpage into data
          url = 'https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)'
          gdp = rq.get(url)

          ## print out the first 200 characters to see what it looks like
          gdp.text[0 : 99]
          [50]:
          '<!DOCTYPE html>\n<html class="client-nojs vector-feature-language-in-header-enabled vector-feature-l'
          [51]:
          # read page into bs4
          bs4page = bs4.BeautifulSoup(gdp.text, 'html.parser')
          tables = bs4page.find_all('table',{'class':"wikitable"})
          [52]:
          from io import StringIO

          # Read the table from the StringIO object into pandas
          # Note most recent version of pandas won't accept a string as input, it needs to be passed through stringio
          gdp = pd.read_html(StringIO(str(tables[0])))[0]

          # drop missing data
          gdp = gdp.dropna()

          # rename columns
          gdp = gdp.rename(columns={'Country/Territory': 'Country','UN region' : 'Region','IMF[1][13]': 'IMF', 'World Bank[14]' : 'WorldBank', 'United Nations[15]':'UnitedNations'})

          # Remove "world" data(the first row; index 0)
          gdp = gdp.iloc[1:]

          # Remove and rename header row
          gdp.columns = gdp.iloc[0:8]
          gdp.columns = ['Country', 'Region', 'IMF_Forecast', 'IMF_Year','WoldBank_Estimate','WorldBank_Year','UN_Estimate','UN_Year']

          # display table
          gdp.head()
          [52]:
          Country Region IMF_Forecast IMF_Year WoldBank_Estimate WorldBank_Year UN_Estimate UN_Year
          1 United States Americas 26949643 2023 25462700 2022 23315081 2021
          2 China Asia 17700899 [n 1]2023 17963171 [n 3]2022 17734131 [n 1]2021
          3 Germany Europe 4429838 2023 4072192 2022 4259935 2021
          4 Japan Asia 4230862 2023 4231141 2022 4940878 2021
          5 India Asia 3732224 2023 3385090 2022 3201471 2021
          [53]:
          # Extract only the relevant columns
          imf = gdp[['Country', 'Region', 'IMF_Forecast']]
          [54]:
          # Rename IMF column
          imf = imf.rename(columns={'IMF_Forecast' : 'Forecast'})

          print(imf.head())
                   Country    Region  Forecast
          1  United States  Americas  26949643
          2          China      Asia  17700899
          3        Germany    Europe   4429838
          4          Japan      Asia   4230862
          5          India      Asia   3732224
          
          [55]:
          # Check Forecast data type
          print(imf['Forecast'].dtypes)
          object
          
          [56]:
          import numpy as np

          # Replace non-numeric values with NaN
          imf['Forecast'] = imf['Forecast'].replace('—', np.nan)

          # Convert 'Forecast' column to numeric data type
          imf['Forecast'] = pd.to_numeric(imf['Forecast'], errors='coerce')

          # Filter rows where 'Forecast' column is non-zero
          imf = imf.loc[imf['Forecast'] != 0]

          # Reset index if needed
          imf.reset_index(drop=True, inplace=True)

          # Show data type of 'Forecast' column
          print(imf['Forecast'].dtypes)
          float64
          
          [57]:
          # Convert IMF to long (unstack converts to tuple)
          page = 'IMF Forecasted GDP (USD in Millions)'
          y_imf = gdp[gdp['IMF_Forecast'] == page].drop(['IMF_Year','WoldBank_Estimate','WorldBank_Year','UN_Estimate','UN_Year'], axis=1).unstack()

          # Check
          print(imf[0:])
          y = np.asarray([10, 20, 30, 40, 50])
          y = y[1 : y.size] - y[0 : (y.size - 1)]
          print(y)
                     Country    Region    Forecast
          0    United States  Americas  26949643.0
          1            China      Asia  17700899.0
          2          Germany    Europe   4429838.0
          3            Japan      Asia   4230862.0
          4            India      Asia   3732224.0
          ..             ...       ...         ...
          207          Palau   Oceania       267.0
          208       Kiribati   Oceania       246.0
          209          Nauru   Oceania       150.0
          210     Montserrat  Americas         NaN
          211         Tuvalu   Oceania        63.0
          
          [212 rows x 3 columns]
          [10 10 10 10]
          
          [58]:
          import plotly.express as px

          # Plot stacked bar of countries within regions using the IMF numbers
          fig = px.bar(imf, x = "Region", y = "Forecast", color = "Country", title='IMF Forecasted GDP by Country',
          labels={'Forecast': 'GDP (USD Million)', 'Region': 'UN Region', 'Country': 'Country'})

          fig.show()
          /opt/tljh/user/lib/python3.10/site-packages/plotly/express/_core.py:2065: FutureWarning:
          
          When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass `(name,)` instead of `name` to silence this warning.
          
          
          AmericasAsiaEuropeOceaniaAfrica010M20M30M40M
          CountryUnited StatesChinaGermanyJapanIndiaUnited KingdomFranceItalyBrazilCanadaRussiaMexicoSouth KoreaAustraliaSpainIndonesiaTurkeySaudi ArabiaNetherlandsSwitzerlandPolandTaiwanBelgiumArgentinaSwedenIrelandNorwayAustriaIsraelThailandUnited Arab EmiratesSingaporeBangladeshPhilippinesVietnamMalaysiaDenmarkEgyptNigeriaHong KongSouth AfricaIranColombiaRomaniaChilePakistanCzech RepublicFinlandIraqPortugalPeruKazakhstanNew ZealandGreeceQatarAlgeriaHungaryUkraineKuwaitEthiopiaMoroccoSlovakiaCubaDominican RepublicEcuadorPuerto RicoKenyaOmanBulgariaGuatemalaAngolaVenezuelaUzbekistanLuxembourgCosta RicaTanzaniaPanamaTurkmenistanCroatiaIvory CoastLithuaniaAzerbaijanGhanaUruguaySerbiaMyanmarSri LankaBelarusSloveniaDR CongoUgandaTunisiaJordanCameroonBoliviaLatviaBahrainParaguayEstoniaNepalLibyaMacauLebanonEl SalvadorHondurasZimbabweCyprusPapua New GuineaSenegalCambodiaIcelandGeorgiaZambiaTrinidad and TobagoBosnia and HerzegovinaHaitiSudanArmeniaGuineaAlbaniaMozambiqueMaliYemenBurkina FasoBotswanaMaltaBeninSyriaGabonPalestineMongoliaJamaicaNicaraguaNigerNorth KoreaGuyanaMoldovaNorth MacedoniaMadagascarBruneiAfghanistanMauritiusCongoLaosRwandaBahamasMalawiKyrgyzstanNamibiaChadTajikistanSomaliaKosovoMauritaniaNew CaledoniaEquatorial GuineaTogoMonacoBermudaMontenegroMaldivesSouth SudanBarbadosFrench PolynesiaCayman IslandsFijiEswatiniLiberiaDjiboutiArubaAndorraSurinameSierra LeoneGreenlandBelizeBurundiCentral African RepublicCuraçaoBhutanCape VerdeSaint LuciaGambiaLesothoEritreaSeychellesZanzibarEast TimorSan MarinoGuinea-BissauAntigua and BarbudaSolomon IslandsSint MaartenBritish Virgin IslandsComorosGrenadaVanuatuTurks and Caicos IslandsSaint Kitts and NevisSaint Vincent and the GrenadinesSamoaDominicaSão Tomé and PríncipeTongaMicronesiaCook IslandsAnguillaMarshall IslandsPalauKiribatiNauruMontserratTuvaluIMF Forecasted GDP by CountryUN RegionGDP (USD Million)
          plotly-logomark
          [59]:
          Selection deleted
          # Save the plot as an HTML file
          fig.write_html('stacked_bars.html')
          html_file = 'stacked_bars.html'

          # Convert the Plotly figure to an HTML string
          plot_html = fig.to_html(full_html=False)

          # Write the HTML string to an HTML file
          with open('stacked_bars.html', 'w') as f:
          f.write(plot_html)
          ## Might delete

          Might delete¶

          [22]:
          # Select GDP source, drop everyrthing, convert to long (unstack converts to tuple)
          y_imf = imf[imf['Forecast'] == page], (axis == 1).unstack()

          # Convert from tuple to array
          y_imf = np.asarray(y_imf)

          # Get the first non zero entry
          y_imf = y_imf[np.min(np.where(y_imf != 0)) : y_imf.size]
          ---------------------------------------------------------------------------
          NameError                                 Traceback (most recent call last)
          Cell In[22], line 2
                1 # Select GDP source, drop everyrthing, convert to long (unstack converts to tuple)
          ----> 2 y_imf = imf[imf['Forecast'] == page], (axis == 1).unstack()
                4 # Convert from tuple to array
                5 y_imf = np.asarray(y_imf)  
          
          NameError: name 'axis' is not defined
          [24]:
          import plotly.express as px
          from jinja2 import Template

          #gdp = px.data.gapminder().query("Region == 'Americas','Asia','Europe','Oceania','Africa'")
          px.bar(gdp, x = "Region", y = "IMF_Forecast", color = "Country", title='IMF Forecasted GDP by Country',
          labels={'IMF_Forecast': 'GDP (USD Million)', 'Region': 'UN Region', 'Country': 'Country'})

          stacked_bars=r"stacked_bars.html"
          input_template_path = r"stacked_bars.html"

          plotly_jinja_data = {"fig":fig.to_html(full_html=False)}
          #consider also defining the include_plotlyjs parameter to point to an external Plotly.js as described above

          with open(stacked_bars, "w", encoding="utf-8") as output_file:
          with open(input_template_path) as template_file:
          j2_template = Template(template_file.read())
          output_file.write(j2_template.render(plotly_jinja_data))

          fig.show()
          /opt/tljh/user/lib/python3.10/site-packages/plotly/express/_core.py:2065: FutureWarning:
          
          When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass `(name,)` instead of `name` to silence this warning.
          
          
          AmericasAsiaEuropeOceaniaAfrica010M20M30M40M
          CountryUnited StatesChinaGermanyJapanIndiaUnited KingdomFranceItalyBrazilCanadaRussiaMexicoSouth KoreaAustraliaSpainIndonesiaTurkeyNetherlandsSaudi ArabiaSwitzerlandPolandTaiwanBelgiumArgentinaSwedenIrelandNorwayAustriaIsraelThailandUnited Arab EmiratesSingaporeBangladeshPhilippinesVietnamMalaysiaDenmarkEgyptNigeriaHong KongSouth AfricaIranColombiaRomaniaChilePakistanCzech RepublicFinlandIraqPortugalPeruKazakhstanNew ZealandGreeceQatarAlgeriaHungaryUkraineKuwaitEthiopiaMoroccoSlovakiaCubaDominican RepublicEcuadorPuerto RicoKenyaOmanBulgariaGuatemalaAngolaVenezuelaUzbekistanLuxembourgCosta RicaTanzaniaPanamaTurkmenistanCroatiaIvory CoastLithuaniaAzerbaijanGhanaUruguaySerbiaMyanmarSri LankaBelarusSloveniaDR CongoUgandaTunisiaJordanCameroonBoliviaLatviaBahrainParaguayEstoniaNepalLibyaMacauLebanonEl SalvadorHondurasZimbabweCyprusPapua New GuineaSenegalCambodiaIcelandGeorgiaZambiaTrinidad and TobagoBosnia and HerzegovinaHaitiSudanArmeniaGuineaAlbaniaMozambiqueMaliYemenBurkina FasoBotswanaMaltaBeninSyriaGabonPalestineMongoliaJamaicaNicaraguaNigerNorth KoreaGuyanaMoldovaNorth MacedoniaMadagascarBruneiAfghanistanMauritiusCongoLaosRwandaBahamasMalawiKyrgyzstanNamibiaChadTajikistanSomaliaKosovoMauritaniaNew CaledoniaEquatorial GuineaTogoMonacoBermudaMontenegroMaldivesSouth SudanBarbadosFrench PolynesiaCayman IslandsFijiEswatiniLiberiaDjiboutiArubaAndorraSurinameSierra LeoneGreenlandBelizeBurundiCentral African RepublicCuraçaoBhutanCape VerdeSaint LuciaGambiaLesothoEritreaSeychellesZanzibarEast TimorSan MarinoGuinea-BissauAntigua and BarbudaSolomon IslandsSint MaartenBritish Virgin IslandsComorosGrenadaVanuatuTurks and Caicos IslandsSaint Kitts and NevisSaint Vincent and the GrenadinesSamoaDominicaSão Tomé and PríncipeTongaMicronesiaCook IslandsAnguillaMarshall IslandsPalauKiribatiNauruMontserratTuvaluIMF Forecasted GDP by CountryUN RegionGDP (USD Million)
          plotly-logomark
          # Part 2

          Part 2¶

          [29]:
          import pandas as pd
          import plotly.express as px
          import plotly.graph_objects as go
          import urllib, json
          import numpy as np
          [30]:
          # use raw file for csv
          dat = pd.read_csv("https://raw.githubusercontent.com/smart-stats/ds4bio_book/main/book/assetts/kirby21.csv").drop(['Unnamed: 0'], axis = 1)
          dat.head()
          [30]:
          id roi volume
          0 127 Telencephalon_L 531111
          1 127 Telencephalon_R 543404
          2 127 Diencephalon_L 9683
          3 127 Diencephalon_R 9678
          4 127 Mesencephalon 10268
          [41]:
          ## load in the hierarchy information
          url = "https://raw.githubusercontent.com/bcaffo/MRIcloudT1volumetrics/master/inst/extdata/multilevel_lookup_table.txt"
          multilevel_lookup = pd.read_csv(url, sep = "\t").drop(['Level5'], axis = 1)
          multilevel_lookup = multilevel_lookup.rename(columns = {
          "modify" : "roi",
          "modify.1" : "level4",
          "modify.2" : "level3",
          "modify.3" : "level2",
          "modify.4" : "level1"})
          multilevel_lookup = multilevel_lookup[['roi', 'level4', 'level3', 'level2', 'level1']]
          multilevel_lookup.head()
          [41]:
          roi level4 level3 level2 level1
          0 SFG_L SFG_L Frontal_L CerebralCortex_L Telencephalon_L
          1 SFG_R SFG_R Frontal_R CerebralCortex_R Telencephalon_R
          2 SFG_PFC_L SFG_L Frontal_L CerebralCortex_L Telencephalon_L
          3 SFG_PFC_R SFG_R Frontal_R CerebralCortex_R Telencephalon_R
          4 SFG_pole_L SFG_L Frontal_L CerebralCortex_L Telencephalon_L
          [42]:
          ## Load in the subject data
          id = 127
          subjectData = pd.read_csv("https://raw.githubusercontent.com/smart-stats/ds4bio_book/main/book/assetts/kirby21AllLevels.csv")
          subjectData = subjectData.loc[(subjectData.type == 1) & (subjectData.level == 5) & (subjectData.id == id)]
          subjectData = subjectData[['roi', 'volume']]
          ## Merge the subject data with the multilevel data
          subjectData = pd.merge(subjectData, multilevel_lookup, on = "roi")
          subjectData = subjectData.assign(icv = "ICV")
          subjectData = subjectData.assign(comp = subjectData.volume / np.sum(subjectData.volume))
          subjectData.head()
          [42]:
          roi volume level4 level3 level2 level1 icv comp
          0 SFG_L 12926 SFG_L Frontal_L CerebralCortex_L Telencephalon_L ICV 0.009350
          1 SFG_R 10050 SFG_R Frontal_R CerebralCortex_R Telencephalon_R ICV 0.007270
          2 SFG_PFC_L 12783 SFG_L Frontal_L CerebralCortex_L Telencephalon_L ICV 0.009247
          3 SFG_PFC_R 11507 SFG_R Frontal_R CerebralCortex_R Telencephalon_R ICV 0.008324
          4 SFG_pole_L 3078 SFG_L Frontal_L CerebralCortex_L Telencephalon_L ICV 0.002227
          [43]:
          fig = px.sunburst(subjectData, path=['icv', 'level1', 'level2', 'level3', 'level4', 'roi'],
          values='comp', width=800, height=800)
          fig.show()
          ICVTelencephalon_RTelencephalon_LMetencephalonCSFDiencephalon_LDiencephalon_RMesencephalonMyelencephalonCerebralCortex_RWhiteMatter_RCerebralNucli_RCerebralCortex_LWhiteMatter_LCerebralNucli_LMetencephalon_RMetencephalon_LVentricleSulcus_LSulcus_RVentricle Thalamus_LBasalForebrain_LThalamus_RBasalForebrain_RMesencephalon_RMesencephalon_LMyelencephalon_RMyelencephalon_LFrontal_RTemporal_RParietal_ROccipital_RLimbic_RInsula_RAnteriorWM_RPosteriorWM_RInferiorWM_RLimbicWM_RCorpusCallosum_RBasalGang_RLimbic_RFrontal_LTemporal_LParietal_LOccipital_LLimbic_LInsula_LAnteriorWM_LPosteriorWM_LInferiorWM_LLimbicWM_LCorpusCallosum_LBasalGang_LLimbic_LCerebellum_RPons_RCerebellum_LPons_LLateralVentricle_LLateralVentricle_RIV_ventricleIII_ventricleFrontSul_LParietSul_LSylvianFissureExt_LCentralSul_LOcciptSul_LCinguSul_LTempSul_LFrontSul_RParietSul_RSylvianFissureExt_ROcciptSul_RCentralSul_RCinguSul_RTempSul_RLateralVentricle_LLateralVentricle_RThalamus_LBasalForebrain_LThalamus_RBasalForebrain_Rmidbrain_Rmidbrain_LMedulla_RMedulla_LMFG_RSFG_RPrCG_RIFG_ROG_RRG_RMTG_RSTG_RFuG_RITG_RAG_RPoCG_RSMG_RSPG_RPrCu_RMOG_RLG_RCu_RIOG_RSOG_RCingulate_RHippo_RLimbic_RInsula_RPeripheralFrontalWM_Rant_DPWM_RPVA_anterior_RPeripheralParietalWM_RPeripheralOccipitalWM_Rpost_DPWM_RPVA_posterior_RPeripheralTemporalWM_Rinf_DPWM_RPLIC_RALIC_RPVA_posterior_RPeripheralCingulateWM_RCGC_RCGH_RFx/ST_RFx_RSCC_RBCC_RGCC_RPut_RCaud_RGP_RBasalForebrain_RCaudate_tail_RAmyg_RSFG_LMFG_LPrCG_LIFG_LOG_LRG_LMTG_LSTG_LFuG_LITG_LPoCG_LSMG_LSPG_LAG_LPrCu_LMOG_LLG_LCu_LIOG_LSOG_LCingulate_LHippo_LLimbic_LInsula_LPeripheralFrontalWM_Lant_DPWM_LPVA_anterior_LPeripheralParietalWM_LPeripheralOccipitalWM_Lpost_DPWM_LPVA_posterior_LPeripheralTemporalWM_Linf_DPWM_LPLIC_LALIC_LPVA_posterior_LPeripheralCingulateWM_LCGC_LCGH_LFx/ST_LFx_LSCC_LBCC_LGCC_LPut_LCaud_LGP_LBasalForebrain_LCaudate_tail_LAmyg_LCerebellum_RCerebellumWM_RPons_RCerebellum_LCerebellumWM_LPons_LAnteriorLateralVentricle_LPosteriorLateralVentricle_LInferiorLateralVentricle_LAnteriorLateralVentricle_RPosteriorLateralVentricle_RInferiorLateralVentricle_RIV_ventricleIII_ventricleFrontSul_LParietSul_LSylTempSul_LSylFrontSul_LSylParieSul_LCentralSul_LOcciptSul_LCinguSul_LTempSul_LFrontSul_RParietSul_RSylTempSul_RSylFrontSul_RSylParieSul_ROcciptSul_RCentralSul_RCinguSul_RTempSul_RAnteriorLateralVentricle_LAnteriorLateralVentricle_RThalamus_LBasalForebrain_LThalamus_RBasalForebrain_Rmidbrain_Rmidbrain_LMedulla_RMedulla_LMFG_DPFC_RMFG_RSFG_PFC_RSFG_RSFG_pole_RPrCG_RIFG_opercularis_RIFG_orbitalis_RIFG_triangularis_RMFOG_RLFOG_RRG_RMTG_RMTG_R_poleSTG_RSTG_R_poleFuG_RITG_RAG_RPoCG_RSMG_RSPG_RPrCu_RMOG_RLG_RCu_RIOG_RSOG_Rdorsal_ACC_RPCC_Rrostral_ACC_Rsubgenual_ACC_Rsubcallosal_ACC_RHippo_RFimbria_RPHG_RENT_RInsula_RPrCWM_RSFWM_PFC_RSFWM_RMFWM_RMFWM_DPFC_RIFWM_opercularis_RIFWM_triangularis_RRGWM_RIFWM_orbitalis_RMFOWM_RLFOWM_RSFWM_pole_RSCR_RACR_RSFO_RPVWa_RPoCWM_RSLF_RSPWM_RAGWM_RSMWM_RPrCuWM_RMOWM_RLGWM_RCuWM_RSOWM_RIOWM_RPCR_RPVWp_RMTWM_RSTWM_RFuWM_RITWM_RMTWM_R_poleSTWM_R_polePTR_RSS_REC_RRLIC_RIFO_RECCL_RPLIC_RALIC_RPVWl_RPCCWM_RdorsalWM_ACC_RsubgenualWM_ACC_RsubcallosalWM_ACC_RrostralWM_ACC_RCGC_RCGH_RFx/ST_RFx_RSCC_RBCC_RGCC_RPut_RCaud_RGP_RNucAccumbens_RCaudate_tail_RAmyg_RSFG_LSFG_PFC_LSFG_pole_LMFG_DPFC_LMFG_LPrCG_LIFG_orbitalis_LIFG_triangularis_LIFG_opercularis_LMFOG_LLFOG_LRG_LMTG_LMTG_L_poleSTG_LSTG_L_poleFuG_LITG_LPoCG_LSMG_LSPG_LAG_LPrCu_LMOG_LLG_LCu_LIOG_LSOG_Ldorsal_ACC_LPCC_Lrostral_ACC_Lsubgenual_ACC_Lsubcallosal_ACC_LHippo_LFimbria_LPHG_LENT_LInsula_LPrCWM_LSFWM_PFC_LSFWM_LMFWM_LMFWM_DPFC_LIFWM_triangularis_LIFWM_orbitalis_LRGWM_LLFOWM_LMFOWM_LIFWM_opercularis_LSFWM_pole_LSCR_LACR_LSFO_LPVWa_LPoCWM_LSPWM_LSLF_LSMWM_LAGWM_LPrCuWM_LMOWM_LLGWM_LCuWM_LSOWM_LIOWM_LPCR_LPVWp_LMTWM_LSTWM_LITWM_LFuWM_LMTWM_L_poleSTWM_L_polePTR_LSS_LEC_LRLIC_LIFO_LECCL_LPLIC_LALIC_LPVWl_LPCCWM_LdorsalWM_ACC_LrostralWM_ACC_LsubgenualWM_ACC_LsubcallosalWM_ACC_LCGC_LCGH_LFx/ST_LFx_LSCC_LBCC_LGCC_LPut_LCaud_LGP_LNucAccumbens_LCaudate_tail_LAmyg_LCerebellumGM_RCerebellumWM_RMCP_cb_RICP_cb_RMCP_RCST_RML_RSCP_RPCT_RPons_RCerebellumGM_LCerebellumWM_LMCP_cb_LICP_cb_LMCP_LCST_LPCT_LSCP_LML_LPons_LLV_body_LLV_Frontal_LLV_atrium_LLV_Occipital_LLV_Inferior_LLV_body_RLV_Frontal_RLV_atrium_RLV_Occipital_RLV_Inferior_RIV_ventricleIII_ventricleFrontSul_LParietSul_LSylTempSul_LSylFrontSul_LSylParieSul_LCentralSul_LOcciptSul_LCinguSul_LTempSul_LFrontSul_RParietSul_RSylTempSul_RSylFrontSul_RSylParieSul_ROcciptSul_RCentralSul_RCinguSul_RTempSul_RChroid_LVetc_LChroid_LVetc_RThalamus_LBasalForebrain_LHypoThalamus_LCl_LMammillary_LThalamus_RBasalForebrain_RHypoThalamus_RCl_RMammillary_RMidbrain_RCP_RRedNc_RSnigra_RMidbrain_LCP_LSnigra_LRedNc_LMedulla_RICP_RMedulla_LICP_L
          plotly-logomark
          [44]:
          # Create Sankey diagram
          fig = go.Figure(data=[go.Sankey(
          node=dict(
          pad=15,
          thickness=20,
          line=dict(color="black", width=0.5),
          label=['ICV', 'Telencephalon_L', 'Telencephalon_R', 'CerebralCortex_L', 'CerebralCortex_R', 'Frontal_L', 'Frontal_R', 'SFG_L', 'SFG_R', 'SFG_PFC_L', 'SFG_PFC_R', 'SFG_pole_L'],
          ),
          link=dict(
          source=[0, 0, 1, 1, 2, 2, 3, 3, 4, 4], # indices correspond to labels
          target=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
          value=subjectData['comp'].tolist()
          ))])
          [45]:
          # Update layout
          fig.update_layout(title_text="Subject 127 Data as Sankey Diagram", font_size=10)

          # Show plot
          fig.show()
          ICVTelencephalon_LTelencephalon_RCerebralCortex_LCerebralCortex_RFrontal_LFrontal_RSFG_LSFG_RSFG_PFC_LSFG_PFC_R
          Subject 127 Data as Sankey Diagram
          plotly-logomark
          [60]:
          # Save the plot as an HTML file
          fig.write_html('sankey.html')
          html_file = 'sankey.html'

          # Convert the Plotly figure to an HTML string
          plot_html = fig.to_html(full_html=False)

          # Write the HTML string to an HTML file
          with open('sankey.html', 'w') as f:
          f.write(plot_html)
          # Links to Webpage

          ## Stacked Bars


          ## Sankey Diagram

          Links to Webpage¶

          Stacked Bars¶

          Sankey Diagram¶

          No properties to inspect.

          Kernel usage not available

          Switch to a notebook or console to see kernel usage details.

          -

          Variables

          Callstack

            Breakpoints

            Source

            9
            1

            Kernel Sources

              0
              0
              ipythongfm
              No Kernel
              Mem: 125.25 MB
              Uploading…

              1
              sankey.html
              Spaces: 4
              Ln 1, Col 1
              Mode: Command
              • Console
              • Change Kernel…
              • Clear Console Cells
              • Close and Shut Down…
              • Insert Line Break
              • Interrupt Kernel
              • New Console
              • Restart Kernel…
              • Run Cell (forced)
              • Run Cell (unforced)
              • Show All Kernel Activity
              • Debugger
              • Breakpoints on exception
              • Evaluate Code
                Evaluate Code
              • Next
                Next
                F10
              • Pause
                Pause
                F9
              • Step In
                Step In
                F11
              • Step Out
                Step Out
                Shift+F11
              • Terminate
                Terminate
                Shift+F9
              • Display Languages
              • English
                English
              • Extension Manager
              • Enable Extension Manager
              • File Operations
              • Autosave Documents
              • Download
                Download the file to your computer
              • Duplicate HTML File
              • Open from Path…
                Open from path
              • Open from URL…
                Open from URL
              • Reload HTML File from Disk
                Reload contents from disk
              • Revert HTML File to Checkpoint…
                Revert contents to previous checkpoint
              • Save HTML File
                Save and create checkpoint
                Ctrl+S
              • Save HTML File As…
                Save with new path
                Ctrl+Shift+S
              • Show Active File in File Browser
              • Trust HTML File
                Whether the HTML file is trusted. Trusting the file allows scripts to run in it, which may result in security risks. Only enable for files you trust.
              • Help
              • About JupyterLab
              • Jupyter Forum
              • Jupyter Reference
              • JupyterLab FAQ
              • JupyterLab Reference
              • Launch Jupyter Notebook File Browser
              • Licenses
              • Markdown Reference
              • Reset Application State
              • Show Keyboard Shortcuts
                Show relevant keyboard shortcuts for the current active widget
                Ctrl+Shift+H
              • Hub
              • Hub Control Panel
                Open the Hub control panel in a new browser tab
              • Log Out
                Log out of the Hub
              • Image Viewer
              • Flip image horizontally
                H
              • Flip image vertically
                V
              • Invert Colors
                I
              • Reset Image
                0
              • Rotate Clockwise
                ]
              • Rotate Counterclockwise
                [
              • Zoom In
                =
              • Zoom Out
                -
              • Kernel Operations
              • Shut Down All Kernels…
              • Kernel Resource
              • Kernel Usage
                Kernel Usage
              • Launcher
              • New Launcher
                Ctrl+Shift+L
              • Main Area
              • Activate Next Tab
                Ctrl+Shift+]
              • Activate Next Tab Bar
                Ctrl+Shift+.
              • Activate Previous Tab
                Ctrl+Shift+[
              • Activate Previous Tab Bar
                Ctrl+Shift+,
              • Activate Previously Used Tab
                Ctrl+Shift+'
              • Close All Other Tabs
              • Close All Tabs
              • Close Tab
                Alt+W
              • Close Tabs to Right
              • End Search
                Esc
              • Find Next
                Ctrl+G
              • Find Previous
                Ctrl+Shift+G
              • Find…
                Ctrl+F
              • Presentation Mode
              • Reset Default Layout
              • Show Header Above Content
              • Show Left Activity Bar
              • Show Left Sidebar
                Ctrl+B
              • Show Log Console
              • Show Right Activity Bar
              • Show Right Sidebar
              • Show Status Bar
              • Simple Interface
                Ctrl+Shift+D
              • Notebook Cell Operations
              • Change to Code Cell Type
                Y
              • Change to Heading 1
                1
              • Change to Heading 2
                2
              • Change to Heading 3
                3
              • Change to Heading 4
                4
              • Change to Heading 5
                5
              • Change to Heading 6
                6
              • Change to Markdown Cell Type
                M
              • Change to Raw Cell Type
                R
              • Clear Cell Output
                Clear outputs for the selected cells
              • Collapse All Code
              • Collapse All Outputs
              • Collapse Selected Code
              • Collapse Selected Outputs
              • Copy Cell
                Copy this cell
                C
              • Cut Cell
                Cut this cell
                X
              • Delete Cell
                Delete this cell
                D, D
              • Disable Scrolling for Outputs
              • Enable Scrolling for Outputs
              • Expand All Code
              • Expand All Outputs
              • Expand Selected Code
              • Expand Selected Outputs
              • Extend Selection Above
                Shift+K
              • Extend Selection Below
                Shift+J
              • Extend Selection to Bottom
                Shift+End
              • Extend Selection to Top
                Shift+Home
              • Insert Cell Above
                Insert a cell above
                A
              • Insert Cell Below
                Insert a cell below
                B
              • Insert Heading Above Current Heading
                Shift+A
              • Insert Heading Below Current Heading
                Shift+B
              • Merge Cell Above
                Ctrl+Backspace
              • Merge Cell Below
                Ctrl+Shift+M
              • Merge Selected Cells
                Shift+M
              • Move Cell Down
                Move this cell down
                Ctrl+Shift+Down
              • Move Cell Up
                Move this cell up
                Ctrl+Shift+Up
              • Paste Cell Above
                Paste this cell from the clipboard
              • Paste Cell and Replace
              • Paste Cell Below
                Paste this cell from the clipboard
                V
              • Redo Cell Operation
                Shift+Z
              • Render Side-by-Side
                Shift+R
              • Run Selected Cell
                Run this cell and advance
                Shift+Enter
              • Run Selected Cell and Do not Advance
                Ctrl+Enter
              • Run Selected Cell and Insert Below
                Alt+Enter
              • Run Selected Text or Current Line in Console
              • Select Cell Above
                K
              • Select Cell Below
                J
              • Select Heading Above or Collapse Heading
                Left
              • Select Heading Below or Expand Heading
                Right
              • Set side-by-side ratio
              • Split Cell
                Ctrl+Shift+-
              • Undo Cell Operation
                Z
              • Notebook Operations
              • Change Kernel…
              • Clear Outputs of All Cells
                Clear all outputs of all cells
              • Close and Shut Down Notebook
              • Collapse All Headings
                Ctrl+Shift+Left
              • Deselect All Cells
              • Enter Command Mode
                Ctrl+M
              • Enter Edit Mode
                Enter
              • Expand All Headings
                Ctrl+Shift+Right
              • Interrupt Kernel
                Interrupt the kernel
              • New Console for Notebook
              • New Notebook
                Create a new notebook
              • Open with Voilà in New Browser Tab
              • Reconnect to Kernel
              • Render All Markdown Cells
              • Render Notebook with Voilà
              • Restart Kernel and Clear Outputs of All Cells…
                Restart the kernel and clear all outputs of all cells
              • Restart Kernel and Debug…
                Restart Kernel and Debug…
              • Restart Kernel and Run All Cells…
                Restart the kernel and run all cells
              • Restart Kernel and Run up to Selected Cell…
              • Restart Kernel…
                Restart the kernel
              • Run All Above Selected Cell
              • Run All Cells
                Run all cells
              • Run Selected Cell and All Below
              • Save and Export Notebook: Asciidoc
              • Save and Export Notebook: Executable Script
              • Save and Export Notebook: HTML
              • Save and Export Notebook: LaTeX
              • Save and Export Notebook: Markdown
              • Save and Export Notebook: PDF
              • Save and Export Notebook: Qtpdf
              • Save and Export Notebook: Qtpng
              • Save and Export Notebook: ReStructured Text
              • Save and Export Notebook: Reveal.js Slides
              • Save and Export Notebook: Webpdf
              • Select All Cells
                Ctrl+A
              • Show Line Numbers
              • Toggle Collapse Notebook Heading
              • Trust Notebook
              • Other
              • Open in Jupyter Notebook
                Notebook
              • Settings
              • Advanced Settings Editor
              • Settings Editor
              • Show Contextual Help
              • Show Contextual Help
                Live updating code documentation from the active kernel
              • Terminal
              • Decrease Terminal Font Size
              • Increase Terminal Font Size
              • New Terminal
                Start a new terminal session
              • Refresh Terminal
                Refresh the current terminal session
              • Use Terminal Theme: Dark
                Set the terminal theme
              • Use Terminal Theme: Inherit
                Set the terminal theme
              • Use Terminal Theme: Light
                Set the terminal theme
              • Text Editor
              • Decrease Font Size
              • Increase Font Size
              • New Markdown File
                Create a new markdown file
              • New Python File
                Create a new Python file
              • New R File
                Create a new R file
              • New Text File
                Create a new text file
              • Spaces: 1
              • Spaces: 2
              • Spaces: 4
              • Spaces: 4
              • Spaces: 8
              • Theme
              • Decrease Code Font Size
              • Decrease Content Font Size
              • Decrease UI Font Size
              • Increase Code Font Size
              • Increase Content Font Size
              • Increase UI Font Size
              • Theme Scrollbars
              • Use Theme: JupyterLab Dark
              • Use Theme: JupyterLab Light